<?php


function checkTagName($name=''){
	$badTags = "{}:;,./?[~!!@#$%^&*()\"_+|`-=<>\\！@#￥%……&*（）——+|·-=【】；：'《》？，'。、]  " ;
	$len = strlen($badTags);
	for($i=0;$i < $len ; $i++){
		$currChar = subString( $badTags ,1 , $i );
		$pos = strpos( $name , $currChar );
		if( $pos  )
			return false;
	}
	return true;
}

function getTag($id,$target = '_blank'){
	global $dbs;
	$lists = $dbs-> select('SELECT * FROM `'.DB_PRE.'filetag` WHERE `parentId` = '. $id .' ORDER BY `id` DESC  ');
	$html = '';
	foreach($lists as $list){
		$name = getTagName($list['tag'],$list['tagMenu']);
		$html .= '<a href="'.urlRewrite('option=list&id='.$list['tag'] .'!'. $list['tagMenu']) .'"  target="'.$target.'">'. $name .'</a>, ';
	}
	return $html;
}

function getTagName($tag ,$tagMenu){
	global $dbs;
	$lists = $dbs-> select('SELECT * FROM `'.DB_PRE.'tag_menu` WHERE `parentId` = '. $tag .' and `id` = '.$tagMenu );
	$name = $lists[0]['name'];
	return $name;
}

function getTagMenu($all=false,$selecteds = ''){
	global $dbs;
	$selecteds = explode('|',$selecteds);
	$lists = $dbs -> select('SELECT * FROM `'. DB_PRE .'tag` WHERE `show` = 1 ');
	$html = '';
	if($all) $allTitle = '<a class="all">'.lang_all.'</a>';
	foreach($lists as $list){	
		//$html .= '<li class="tagMenu"><label class="highBig" ids="'.$list['id'].'">'. $list['name'] .'</label>';
		$name = $list['name'] == '添加标签' ? lang_add_tag : $list['name'];
		$html .= '<li class="tagMenu"><label class="highBig" ids="'.$list['id'].'">'. $name .'</label>';		
		$menus = $dbs -> select('SELECT * FROM `'. DB_PRE .'tag_menu` WHERE `parentId` = '. $list['id'] .' ');
		$html .= $allTitle ;
		foreach($menus as $menu){
			$class = '';
			foreach($selecteds as $selected){
				$selected = explode('!',$selected);
				in_array( $menu['id'] , explode(',',$selected[1]) ) ? $class = ' class="active" ' : '';				 
			}			
			$html .= '<a ids="'.$menu['id'].'" '.$class.'>'. $menu['name'] .'</a>';	
		}	
		$html .='</li>';
	}
	echo $html;	
}
function getMedia($id){
	global $dbs;
	$list = $dbs -> select('SELECT * FROM `'.DB_PRE.'file` WHERE `id` ='. (int)$id );
	return $list[0];
}


function getFileLists($tags, $user_id = 0 , $target = '_blank',$orderBy = 'id'){
	global $dbs , $user , $fromType,$encrypt ;
	$subStrLen = FILE_LIST_DESCRIPTION_LEN ? FILE_LIST_DESCRIPTION_LEN : 100 ;
	$html = '<h1>'. $fromType .'</h1>';
	if( count($tags) ==0 ){
		//echo '<h1>这个标签下面没有内容。</h1>';
	}
	$html .='<table width="100%" border="0" cellspacing="1" cellpadding="3">'
			  .'<tr class="listTitle">'
				.'<th class="works">作品</th>'
				//.'<th class="name">名称</th>'
				//.'<th class="time">时间</th>'
				.'<th class="score">得分</th>'
				//.'<th class="hits">点击</th>'
				//.'<th class="down">下载</th>'
				//.'<th class="comm">评论</th>'
				.'<th class="operate">'.lang_operate.'</th>'
			  .'</tr>';
	$isHave = false ;
	foreach($tags as $tag){
		if( $user_id == 0)
			$sql = 'SELECT * FROM `'.DB_PRE.'file` WHERE `id` = '. $tag['parentId'] .' and `status` = "1" limit 0,1 ' ;
		else
			$sql = 'SELECT * FROM `'.DB_PRE.'file` WHERE `id` = '.$tag['parentId'] .' and `user_id` ='. $user_id .' and `status` = "1" limit 0,1 '  ;

		$lists = $dbs -> select($sql);		
		if(count($lists) != 0 ){
			$isHave = true ;			
			$list = $lists[0];
			$starHtml = '';
			for($i = 1; $i<= 5 ;$i++){
				$class = $i <= $list['star'] ? ' class="a" ' : '';
				$starHtml .= '<i '.$class.'></i>';
			}
			$id  = $encrypt -> code($list['id']);
			$html .='<tr>'
 
				.'<td class="thumbs">
					<div class="itemthumb">
						<a class="beautyImg" title="'.htmlShow($list['name']).'" href="'.urlRewrite('option=media&id='.$id).'" target="'.$target.'"><img src="'.getMediaThumb($list['id']).'" alt="'.htmlShow($list['name']).'" /></a>
					</div>
					<div class="itemdetail">
						<h3 class="itemtitle">
							<a title="'.htmlShow($list['name']).'" href="'.urlRewrite('option=media&id='.$id).'" target="'.$target.'">'.subString(htmlShow($list['name']),60).'</a>
						</h3>
						<p class="itemdate">上传时间：'. date('Y-m-d',strtotime($list['time'])) .'</p>
						<p class="itemtag">标签：'. getTag($list['id'],$target) .'</p>
						<p class="itemstat">
							<span>点击：'. $list['hits'] .'</span>
							<span>下载：'. $list['downTimes'] .'</span>
							<span>评价：'. $list['comments'] .'</span>
						</p>'
						//<p>标识码：<span class="itemid">'.$id.'</span></p>
					.'</div>
				</td>'
				//.'<td align=center>'. date('Y-m-d',strtotime($list['time'])) .'</td>'
				.'<td align=center><span class="star">'.$starHtml.'</span></td>'
				//.'<td align=center>'. $list['hits'] .'</td>'
				//.'<td align=center>'. $list['downTimes'] .'</td>'
				//.'<td align=center>'. $list['comments'] .'</td>'
				.'<td>';
				
				$html .='<span class="action view"><a href="'.urlRewrite('option=media&id='.$id).'">'.lang_view.'</a></span>';
				if( $user_id == $list['user_id'])
					$html .='<span class="action mod"><a href="'.urlWrite('option=creatMedia&id='. $id ) .'">修改作品</a></span><span class="action del"><a href="'.WEB_ROOT_PATH.'?option=userDo&type=action&do=delFile&id='. $id.'">删除作品</a></span>';
				else
					;//$html .= '<span class="action view"><a title="'.htmlShow($list['name']).'" href="./?option=media&id='.$id.'" target="_blank">预览作品</a></span>';
			 $html .='</td>'
			  .'</tr>'
			  .'<tr><td colspan="10" class="compart"><hr /></td></tr>';
		}
	}
	
	if( !$isHave )
		$html .= '<tr><td colspan="10" class="noWorks"><p class="emptylist">未上传任何作品，点击<a href="'.urlRewrite('option=creatMedia').'">这里</a>开始上传。</p></td></tr>';
	
	
	$html .= '</table>';
	echo $html;
}


function initUserLogin($users){	
	$_SESSION['user_id']		=  $users['id'] ;
	$_SESSION['userPowder']		=  $users['powder'] ;
	$_SESSION['userName']		=  $users['userName'] ;
	$_SESSION['nickName']		=  htmlShow($users['nickName']) ;
	$_SESSION['passWord']		=  $users['passWord'] ;	
	$_SESSION['randomPass']		=  $users['randomPass']  ;
	
	setcookie("user_id", $users['id'] , time() + SESSION_TIME * 60);
	
}


function saveUserFace($photoBig,$photoSmall,$user_id){
	global $dbs ;
	//a7974 9837c c5223 5a422 2fa87 36c5a 49d42 9355a
	$userFaceName = substr( md5($_SESSION['userName'] ) , 8 , 16 );
	
	$bigNew 	= saveUserFaceDo($photoBig		,$userFaceName,	USERFACE_BIG_PATH);
	$smallNew	= saveUserFaceDo($photoSmall	,$userFaceName,	USERFACE_PATH);
	
	$photoBig   = str_replace('\\','/',USERFACE_BIG_PATH . $bigNew) ;
	$photoSmall = str_replace('\\','/',USERFACE_PATH    . $smallNew) ;	
	$array['faceBig'] = $photoBig;
	$array['faceSmall'] = $photoSmall;
	$dbs -> update(DB_PRE .'user',$array,' `id` = '.$user_id );
	
	return array('photoBig' => $photoBig,'photoSmall' => $photoSmall);
}

function saveUserFaceDo($photo ,$newName,$path){
	$width = getWidth(ROOTPATH . TMP_PATH . $photo );
	$height = getHeight(ROOTPATH . TMP_PATH . $photo );	
	$type = getFileExt($photo ); 	
	$widthSmall = getWidth(ROOTPATH . TMP_PATH . $photo ); 	
	$newPhoto   = $newName .','.	$width .','. $height .'.'. $type ;	
	rename( ROOTPATH . TMP_PATH . $photo , ROOTPATH . $path . $newPhoto );
	return $newPhoto ;
}


function moveUploadFile($files,$path,$type = 'cut',$comeFrom = TMP_PATH ){
	
	$pathName = str_replace('/','',str_replace(DS,'',$path ));
	$tmpName  = str_replace('/','',str_replace(DS,'',$comeFrom ));
	$comeFromArray = array($tmpName,$pathName);
	
	$maxSize = MAX_FILE_SIZE ? MAX_FILE_SIZE : 100 * 1024 * 1024 ;
	$filesList = '|';
	$pathDate = creatFolder( ROOTPATH . $path );
	$path = $path . $pathDate ;

	$realPath = ROOTPATH . $path;
	
	$root_path_count = strlen(ROOT_PATH);
	
	foreach($files as $file){
		
		//防止客户端提交不正确文件路径
		//$file = str_replace( ROOT_PATH ,'',$file , $replaceCount);
		//
		//$file = preg_replace('/'.$root_path.'/','', $file, 1);
		if( substr( $file ,0,$root_path_count) == ROOT_PATH ){
			$file = substr( $file , $root_path_count) ;
		}
		//echo $file .']';
		 
		$filesCheck = explode('/',$file);
		
		
		if( !in_array($filesCheck[0],$comeFromArray ) ){
			return '';
		}
		
		
		/*
		$fileName = basename($file);
		//$fileRealName = str_replace('\\','/',ROOTPATH . TMP_PATH . $fileName) ;
		$fileRealName = ROOTPATH . TMP_PATH . $pathDate . $fileName ;	
		if( !file_exists( $fileRealName ))
			$fileRealName = ROOTPATH . UPLOADFILE_PATH . $pathDate . $fileName ;
		*/
		$fileRealName = $file ;
		if( file_exists( $fileRealName ) ){			
			
			
			if( count( explode('://',$fileRealName)) > 1 )// 防止客户端发送远程文件
				return '';
			
			$size  = filesize($fileRealName);	
			//防止客户端提交体积过大文件。
			if( $size > MAX_FILE_SIZE || $size < 1 )
				continue ;
			
			// reSize , 防止图片尺寸过大
			//$photo = new photo();
			//$photo -> reSize($fileRealName,PHOTO_MAX_WIDEH,PHOTO_MAX_HEIGHT);	
			
			//print_r($fuck);
			
			
			//防止用户提交危险后缀 , getFileExt 会过滤
			$fileType = getFileExt($fileRealName);	
			
			
			
			
			
			if('jpg' == $fileType || 'jpeg' == $fileType || 'png' == $fileType || 'gif' == $fileType ){
				$width = getWidth($fileRealName);
				$height = getHeight($fileRealName);	
				$fileNewName = date('His',time()).rand(1000,9999).floor(microtime()*10000).rand(1000,9999) .','. $width .'x'. $height.'.'. $fileType ;//不信任客户端提交的文件名.
			}else{
				$fileNewName = date('His',time()).rand(1000,9999).floor(microtime()*10000).rand(1000,9999) . '.'. $fileType ; // 安全策略，不信任客户端提交的文件名.
			}
			
			
			// 检测来源，确认是否在修改文件
			//$filesCheck = explode('/',$files);
			
			//  有多个文件夹，有复制的情况。
			if(  $comeFrom == TMP_PATH )
				$tmpArray = array(  $pathName  );
			else
				$tmpArray = array(  $pathName , $comeFrom  );
				
				
			if( !in_array($filesCheck[0], $tmpArray ) ){
			
				if( $type == 'cut' )
					rename( $fileRealName  , $realPath . $fileNewName);
				else
					copy( $fileRealName  , $realPath . $fileNewName);
				$filesList .= '|'. $path . $fileNewName ;
			}else{
				$filesList .= '|'. $file;
			}
			
		}else{
			$filesList = '||';
		}
	}
	
	
	$filesList = str_replace('||','',$filesList);
	$filesList = str_replace('\\','/',$filesList);
	return $filesList ;
}

function checkFileOwner($files, $field = 'file',$file_id=0,$user_id = 0){
	global $dbs ,$user;
	if(!$files) return '';
	$tmpName  = str_replace('/','',str_replace(DS,'', TMP_PATH ));
	$lists = $dbs -> select('SELECT * FROM `'.DB_PRE.'file` WHERE `id` = '.$file_id);
	$list = $lists[0];

	$oldFiles = explode('|',$list[$field]);
	foreach($files as $file){
		$fileFolder = explode('/',$file);
		if( $fileFolder[0] == $tmpName || $fileFolder[0] == '' )
			continue ;
		else{
			if( $list['user_id'] != $user_id && $user -> powder() < 9 ){
				//echo $file .';';
				//echo $list['user_id'] .'-'. $user_id ;
				exit('{"status":"error","msg":"您没有权限修改."}');		
				return false;
			}
			//echo $file .']' ;
//				print_r($oldFiles);
			if( !in_array($file,$oldFiles ) ){
				
				
				exit('{"status":"error","msg":"这些文件不是您上传的.请通过正常途径上传"}');		
			}
		}
		
	}
	

}


function getPage($page){
	if( $page == '') $page = 'page';
	$pages		= getQuery($page) ;
	$pages		= (int)$pages;
	$pages		=	$pages == 0 ? 1 : $pages;
	return $pages ;
}

function getId($id){
	global $encrypt ;
	if( $id == '') $id = 'id';
	$id			= getQuery($id);
	
	if( '' != $id ){
		$id = $encrypt -> recode($id);
	}	
	$id = (int)$id;	
	return $id ;
}



function getFace($user_id, $type='small'){
	if( $user_id != ''){
		$users = new users();
		$user = $users -> getUser($user_id);
		//urlRewrite('option=attachment&id='. $user_id .'&mediaType=user_thumb' );
		if( $type == 'big')
			$face = WEB_ROOT_PATH .$user['faceBig'];
		else
			$face = WEB_ROOT_PATH .$user['faceSmall'];
	}
	if( '' == $face || WEB_ROOT_PATH == $face )
		$face = USERFACE ;
	
	return $face;
}

function getUserBigFace($face){
	if( '' == $face ) $face = USERFACE_BIG ;
	return $face;
}

function getUserFace($face){
	if( '' == $face ) $face = USERFACE ;
	return $face;
}



function getMediaThumb(&$id){
	global $encrypt;
	$thubm = '';
	if( '' == $id )
		$thubm = MEDIA_THUMB ;
	else
		$thubm = urlRewrite('option=attachment&mediaType=file_thumb&id='.$encrypt -> code($id) .'-1.jpg') ;
	return $thubm ;
}


class mediasTop{
	function getList($orderBy = 'id',$num=0,$style = 'list' , $isPage = false,$isMore = true){
		//$style = grid , list ;
		
		global $dbs, $page,$encrypt;
		$user = new users();		
		$sqlCount = 'SELECT * FROM `'. DB_PRE .'file` WHERE `status` = "1"  ORDER BY `'. $orderBy .'` DESC';
		if( $num == 0 )
			$sql = $sqlCount .' limit '. (($page - 1) *  PAGE_SIZE * 2 ) .' , '. PAGE_SIZE * 2;
		else
			$sql = $sqlCount .' limit 0 , '. $num ;
		$listCount	= $dbs -> select($sqlCount);
		$total			= count($listCount);
		$lists = $dbs -> select($sql);
		$html = '';
		
		if( $style == 'list' ){	
			$html .='<table width="100%" border="0" cellspacing="1" cellpadding="3">'
			  .'<tr class="listTitle">'
				.'<th class="works">'.lang_works.'</th>'
				//.'<th class="name">名称</th>'
				//.'<th class="time">时间</th>'
				.'<th class="score">'.lang_grade.'</th>'
				//.'<th class="hits">点击</th>'
				//.'<th class="down">下载</th>'
				//.'<th class="comm">评论</th>'
				.'<th class="operate">'.lang_operate.'</th>'
			  .'</tr>';
			foreach($lists as $list){
				$id = $encrypt -> code($list['id']);				
				$userInfo = $user -> getUser($list['user_id']);
				$starHtml = '';
				for($i = 1; $i<= 5 ;$i++){
					$class = $i <= $list['star'] ? ' class="a" ' : '';
					$starHtml .= '<i '.$class.'></i>';
				}
				$html .='<tr>'
					.'<td class="thumbs">'
						.'<div class="itemthumb">'
							.'<a class="beautyImg" title="'.htmlShow($list['name']).'" href="'.urlRewrite('option=media&id='.$id).'" target="_blank">'
								.'<img class="thumb" src="'.getMediaThumb($list['id']).'" alt="'.htmlShow($list['name']).'" />'
							.'</a>'
						.'</div>'
						.'<div class="itemdetail">'
							.'<h3 class="itemtitle">'
								.'<a title="'.htmlShow($list['name']).'" href="'.urlRewrite('option=media&id='.$id).'" target="_blank">'.htmlShow($list['name'])
							.'</a></h3>'
							.'<p>'.lang_time.'：'.date('Y-m-d',strtotime($list['time'])) .'</p>'
							.'<p class="tag"><span>'.lang_tag.'：'. getTag($list['id'],$target) .'</span></p>'
							.'<p><span>'.lang_upload.'：<a href="'.urlRewrite('option=home&id='.$list['user_id']) .'" target="_blank">'. htmlShow($userInfo['nickName']) .'</a></p>'
							.'<p><span>'.lang_hits.'：'.$list['hits'].'</span><span>'.lang_download.'：'.$list['downTimes'].'</span><span>'.lang_comment.'：'.$list['comments'].'</span></p>'
						.'</div>'
					.'</td>'
					//.'<td>'. $time[0] .'</td>'
					.'<td><span class="star">'.$starHtml.'</span></td>'
					//.'<td></td>'
					//.'<td></td>'
					//.'<td></td>'
					.'<td><span class="action view"><a href="'.urlRewrite('option=media&id='.$id).'" target="_blank">'.lang_view.'</a></span></td>'
					
					
					
					
				 .'</tr>'
				 .'<tr><td class="compart" colspan="3"><hr /></td></tr>';
			}
			$html .= '</table>';
			if($isMore && $total > $num)
				$html .= '<div class="more"><a href="'.urlRewrite('option=listTop&id='.$orderBy .'&page=1.html').'" target="_blank">'. lang_all .' &gt;</a></div>';
		}else{
			$html .= '<div class="topLists"><ul>';
			foreach($lists as $list){
				$starHtml = '';
				for($i = 1; $i<= 5 ;$i++){
					$class = $i <= $list['star'] ? ' class="a" ' : '';
					$starHtml .= '<i '.$class.'></i>';
				}
				$userInfo = $user -> getUser($list['user_id']);
				$html .= '<li>'
				  .'<a href="'.urlRewrite('option=media&id='.$encrypt -> code($list['id'])) .'" target="_blank"><img class="thumb" src="'.getMediaThumb($list['id']).'" /></a>'
				  .'<h3><a class="thumbTitle" href="'.urlRewrite('option=media&id='.$encrypt -> code($list['id'])) .'" target="_blank">'. htmlShow(subString($list['name'],38)).'</a></h3>'
				  .'<h3 class="star">'.lang_grade.': '.$starHtml.'</h3>'
				  .'<h3>'.lang_upload.': <a href="'.urlRewrite('option=home&id='.$list['user_id']) .'" target="_blank">'. htmlShow($userInfo['nickName']) .'</a></h3>'
				  .'<h1>'. getTag($list['id'],'_blank') .'</h1>'
				.'</li>';
			}
			$html .= '<div class="clear"></div>
				</ul>';
			if($isMore && $total > $num)
				$html .= '<div class="more"><a href="'.urlRewrite('option=listTop&id='.$orderBy .'&page=1.html').'" target="_blank">'. lang_all .' &gt;</a></div>';
			$html .='	
				</div>';
		}
		if($isPage) 
			//$html .= getPages($page,$total,getPageFileUrl() .'&order='. $orderBy ,PAGE_SIZE, PAGE_LEN);
			$html .= getPages($page,$total,getPageFileUrl('', true)  ,PAGE_SIZE * 2, PAGE_LEN,true);
			//urlRewrite('option=listTop&id='.$orderBy .'&page=1.html')
			
		
		return $html;
	}	
}

class hits{
	function add($type,$id=0){
		include( ROOTPATH .'include'. DS .'browser.php');
		global $dbs;
		$id = (int)$id;
		if( 0 >  $id ) return false;
		$array = array();
		
		if('media' == $type){			
			$lists = $dbs -> select('SELECT * FROM `'.DB_PRE.'file` WHERE `id` ='. $id);
			$lists = $lists[0];
			$array['hits'] = $lists['hits'] + 1;
			$dbs -> update( DB_PRE.'file',$array,'`id` ='. $id);
		}
		else if('user' == $type){
			$lists = $dbs -> select('SELECT * FROM `'.DB_PRE.'user` WHERE `id` ='. $id);
			$lists = $lists[0];
			$array['hits'] = $lists['hits'] + 1;
			$dbs -> update( DB_PRE.'user',$array,'`id` ='. $id);
		}else if('task' == $type){
			$lists = $dbs -> select('SELECT * FROM `'.DB_PRE.'task` WHERE `id` ='. $id);
			$lists = $lists[0];
			$array['hits'] = $lists['hits'] + 1;
			$dbs -> update( DB_PRE.'task',$array,'`id` ='. $id);
		}
		unset($array);
		unset($lists);
		
		$Browser = new Browser ;
		$array = array();
		$array['foreign_id'] 	= $id ;
		$array['type'] 			= $type;
		$array['browser']		= $Browser -> getBrowser();
		$array['browserVer'] 	= $Browser -> getVersion();
		$array['ip'] 			= ip();
		$array['created'] 		= date('Y-m-d H:i:s',time());
		$dbs -> insert( DB_PRE.'hits',$array);
	}
}



class userUploadPhoto{
		
	function uploadUserFace($userPhoto,$photoSavePath ,$photoSaveName,$cropWidth=100,$cropHeight=100,$max_file_size){	
		$allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpeg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
		$allowed_image_ext = array_unique($allowed_image_types);	
		$file = $userPhoto;	
		$userfile_name = $file['name'];
		$userfile_tmp = $file['tmp_name'];
		$userfile_size = $file['size'];
	
		$userfile_width = $file['width'];
		$userfile_type = $file['type'];
		$filename = basename($file['name']);
		$file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));	
		if((!empty($file)) && ($file['error'] == 0)) {
			foreach ($allowed_image_types as $mime_type => $ext) {
				if($file_ext==$ext){
					$error = "";
					break;
				}else{
					$error = "仅支持 <strong>".$image_ext."</strong> 格式<br />";
				}			
			}
			if ($userfile_size > ( $max_file_size )) {
				$error.= "错误。图片大小不能超过 ".$max_file."KB ，更换小图片";
			}
			if('' != $error )
				exit($error);
			//$filesName = date('YmdHis',time()).','. floor(microtime()*10000000);	
			$filesName = md5(date('YmdHis') . rand(100,999));
			$tempFile = $file['tmp_name'];
			$fileExt = getFileExt($file['name']);
			//$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
			$targetPath = ROOTPATH . TMP_PATH ;
			$targetFile =  $targetPath . $filesName  .'.'.$fileExt ;
			$localFilePath = TMP_PATH .  $filesName  .'.'.$fileExt ;
			
			if(!file_exists($targetPath)) mkdir($targetPath);
			move_uploaded_file($tempFile,$targetFile);
			return self::cropUserPhoto($targetFile,$photoSavePath,   $photoSaveName ,$cropWidth ,$cropHeight , $type = 'cut' );
		}else{
			$error= "您还没有选择照片呢...";
		}
		if('' != $error )
				exit($error);
	}
	
	function cropUserPhoto($photoSrc, $photoSavePath , $photoSaveName , $targ_w = MEDIA_THUMB_WIDTH ,$targ_h = MEDIA_THUMB_HEIGHT , $type = 'cut'){
		$src = $photoSrc;	
		$jpeg_quality =  JPEG_QUALITY ? JPEG_QUALITY : 95 ;
		$img_r = imagecreatefromjpeg($src);
		$dst_r = imagecreatetruecolor( $targ_w, $targ_h );	
		$width = getImgWidth($src);
		$height = getImgHeight($src);
		$rate = $targ_w / $targ_h;
		if($width > $height * $rate ){
			$cropW = $height * $rate;
			$cropH = $height ;
			$start_x = ($width - $cropW) / 2;
			$start_y = 0;
		}else{
			$cropW = $width;
			$cropH = $width / $rate ;
			$start_x = 0;
			$start_y = ($height - $cropH) / 2;
		}
		
		imagecopyresampled($dst_r,$img_r,0,0,$start_x,$start_y, $targ_w,$targ_h,$cropW,$cropH);
	
		$imageType = getFileExt($src);
		//$name = date('YmdHis',time()) . floor(microtime()*1000).','. $targ_w .','. $targ_h . '.'.$imageType ; 
		$name = $photoSaveName .','. $targ_w .'x'. $targ_h . '.'.$imageType;
		$path =  ROOTPATH .  $photoSavePath ;
		$web_path =  $photoSavePath . $name  ;
		$thumb_image_name = $path . $name;
		switch($imageType) {
			case "gif":
				imagegif($dst_r,$thumb_image_name); 
				break;
			case "jpeg":
			case "jpg":
				imagejpeg($dst_r,$thumb_image_name, $jpeg_quality); 
				break;
			case "png":
				imagepng($dst_r,$thumb_image_name);  
				break;
		}
		if( $type == 'cut' )
			unlink($src);
		return str_replace('\\','/',$web_path); 
	}
}



function getMediaSourceList($media_id,$password, $isNeedPass = true , $type = 'ajax'){
	global $dbs,$encrypt ;
	$media_id	 = (int)$media_id;
	$media_id_Code = $encrypt -> code($media_id);
	$sql = 'SELECT * FROM `'. DB_PRE.'file` WHERE `id` = '. $media_id ;
	$shows		 = $dbs -> select($sql);
	$show 		 = $shows[0];
	if( $password != $show['passWord'] && $isNeedPass )
		exit('{"status":"error","msg":"'.lang_password_error.'."}') ;
	
	$mediaSources			 = explode('|',$show['mediaSource']);
	$mediaSourceTitles		 = explode(SPLIT_STRING , $show['mediaSourceTitles']);
	$i						 = -1;
	
	if( $type == 'ajax'){
		$html					 = '{"status":"ok","msg":"';
		foreach($mediaSources as $mediaSource){
			$i++;
			$html .= '<a class=\"'.creatMediaSourceIco($mediaSource).'\" href=\"'.urlRewrite('option=attachment&mediaType=file&id='. $media_id_Code.'&page='.($i+1).'.'.getFileExt($mediaSource)).'\" target=\"_blank\">'. toText($mediaSourceTitles[$i]) .'</a>  ';
		}
		$html .= '"}';	
	}else{
		foreach($mediaSources as $mediaSource){
			$i++;
			$html .= '<a class="'.creatMediaSourceIco($mediaSource).'" href="'.urlRewrite('option=attachment&mediaType=file&id='. $media_id_Code.'&page='.($i+1).'.'.getFileExt($mediaSource)).'" target="_blank">'. toText($mediaSourceTitles[$i]) .'</a> ';
		}	
	}
	//$html = json_encode($html);
	echo $html ;
}

function creatMediaSourceIco($fileName){
	$class = '';
	$ext = getFileExt($fileName);
	switch($ext){
		case 'gif':
		case 'jpg':
		case 'png':
			$class = 'image';		
		break ;
		
		case 'zip':
		case 'rar':
		case 'gzip':
			$class = 'zip';		
		break ;	
	}
	return $class;
}


class upload{
	function files($file,$savePath,$saveName,$isImageResize = false){
		if (empty($file)) return false;		
		if( $saveName == '')
			$saveName = date('YmdHis',time()).','. floor(microtime()*10000000) . ',' . rand(1000, 9999) ;
		$tempFile = $file['tmp_name'];
		$fileExt = getFileExt($file['name']);
		$targetPath = ROOTPATH  . $savePath ;
		$targetFile = $targetPath . $saveName  .'.'.$fileExt ;
		move_uploaded_file($tempFile,$targetFile);		
		$fileName =  $savePath . '/' .$saveName  .'.'.$fileExt ;
		$fileName = str_replace('\\','/',$fileName);
		$fileName = str_replace('//','/',$fileName);
		self::checkSize($file,$file['size']);
		
		// reSize , 防止图片尺寸过大
		if($isImageResize) {
			$photo = new photo();
			$photo -> reSize($targetFile,PHOTO_MAX_WIDEH,PHOTO_MAX_HEIGHT);			
		}
		return $fileName ;
	}
	
	function checkSize($file,$size){
		$maxSize = MAX_FILE_SIZE ? MAX_FILE_SIZE : 100 * 1024 * 1024 ;
		if( $size > MAX_FILE_SIZE || $size < 1 )
			exit('文件体积太大');
	}
}


class photo{
	function reSize($image,$max_width,$max_height){
		$type = getFileExt($image);
		if($type != 'jpg' && $type != 'jpeg' && $type != 'png' && $type !='gif')
			return ;
		$width = self::getWidth($image);
		$height =  self::getHeight($image);
		if ($width > $max_width || $height > $max_height){			
			$scaleW = $max_width/$width;
			$scaleH = $max_height/$height;			
			$scale = $scaleW  > $scaleH ? $scaleH :   $scaleW;
			$uploaded = self::resizeImage($image,$width,$height,$scale);			
		}else{
			$scale = 1;
			$uploaded = self::resizeImage($image,$width,$height,$scale);
		}	
		return $uploaded ;
	}
	
	function getHeight($image) {
		$size = getimagesize($image);
		$height = $size[1];
		return $height;
	}
	
	function getWidth($image) {
		$size = getimagesize($image);
		$width = $size[0];
		return $width;
	}
	
	function resizeImage($image,$width,$height,$scale) {
		list($imagewidth, $imageheight, $imageType) = getimagesize($image);
		$imageType = image_type_to_mime_type($imageType);
		$newImageWidth = ceil($width * $scale);
		$newImageHeight = ceil($height * $scale);
		$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
		switch($imageType) {
			case "image/gif":
				$source=imagecreatefromgif($image); 
				break;
			case "image/pjpeg":
			case "image/jpeg":
			case "image/jpg":
				$source=imagecreatefromjpeg($image); 
				break;
			case "image/png":
			case "image/x-png":
				$source=imagecreatefrompng($image); 
				break;
		}
		imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
		
		switch($imageType) {
			case "image/gif":
				imagegif($newImage,$image); 
				break;
			case "image/pjpeg":
			case "image/jpeg":
			case "image/jpg":
				imagejpeg($newImage,$image,90); 
				break;
			case "image/png":
			case "image/x-png":
				imagepng($newImage,$image);  
				break;
		}
		
		chmod($image, 0777);
		return $image;
	}
}

function getMediaFiles($mediaSource,$mediaSourceTitles,$fileDescriptions = ''){
	$mediaSource = explode('|',$mediaSource);
	$mediaSourceTitles = explode( SPLIT_STRING ,$mediaSourceTitles);
	$fileDescriptions  = explode( SPLIT_STRING ,$fileDescriptions);
	$mediaSourceCount = count($mediaSource);
	$html = '';
	if( $mediaSource[0] != '' ){
		for( $i = 0 ; $i < $mediaSourceCount ; $i++ ){
			
			$html .= '<div class="uploadifyQueueItem onComplete" file="'.$mediaSource[$i].'">'
					.'<div class="cancel"><a href="#"><img border="0" src="'.WEB_ROOT_PATH.'upload/images/cancel.png"></a></div>'
					.'<span class="fileName"><input type="text" value="'. htmlShow($mediaSourceTitles[$i]) .'" maxlength="30"></span>';
					
				if( '' != $fileDescriptions ){
					$html .= '<span onclick="addMediaTitle(this);" class="addMediaTitle">添加描述 </span>';
						
				}
					$html .= '<span onclick="editMediaTitle(this)" class="editMediaTitle" style="display: '. ('' != $fileDescriptions[$i] ?'inline-block' : '' )    .';"></span>';					
				
				
					$html .= '<span class="percentage"> - 100%</span>'
					.'<div class="uploadifyProgress"><div class="uploadifyProgressBar" style="width: 100%;"></div></div>';
				if( '' != $fileDescriptions ){
					$html .= '<div class="mediaTitle">'
								.'<textarea name="mediaTitle">'.$fileDescriptions[$i].'</textarea>'
								.'<input type="button" value="确定" class="submit" onclick="saveMediaTitle(this)">'
							.'</div>';
				}
			$html .= '</div>';
		}
		return $html;
	}
}


function fileListHtml( $list = array() ){
	include_once( ROOTPATH .'class'. DS .'task.class.php'); 
	include_once( ROOTPATH .'class'. DS .'mediaFile.class.php');
	global $user ,$encrypt ;
	$task = new task ;
	$mediaFile = new mediaFile ;
	$target = '_blank';
	$id  = $encrypt -> code($list['id']);
	$starHtml = '';
	for($i = 1; $i<= 5 ;$i++){
		$class = $i <= $list['star'] ? ' class="a" ' : '';
		$starHtml .= '<i '.$class.'></i>';
	}
	$userInfo = $user -> getUser($list['user_id']);
	 	
	$html ='<tr>'
		.'<td class="thumbs">
			<div class="itemthumb">
				<a class="beautyImg" title="'.htmlShow($list['name']).'" href="'.urlRewrite('option=media&id='.$id).'" target="'.$target.'"><img src="'.getMediaThumb($list['id']).'" alt="'.htmlShow($list['name']).'" /></a>
			</div>
			<div class="itemdetail">
				<h3 class="itemtitle">
					<a title="'.htmlShow($list['name']).'" href="'.urlRewrite('option=media&id='.$id).'" target="'.$target.'">'. htmlShow($list['name'],'<b>') .'</a>
				</h3>
				<p class="itemuploader">上传者：<a target="_blank" href="'.urlRewrite('option=home&id='.$list['user_id']).'">'. htmlShow($userInfo['nickName']) .'</a></p>
				<p class="itemdate">
					
					'.lang_time.'：'. date('Y-m-d',strtotime($list['time']))
					.' <span>'.lang_hits.'：'. $list['hits'] .'</span>
					<span style="display:none">'.lang_download.'：'. $list['downTimes'] .'</span>
					<span>'.lang_appraisal.'：'. $list['comments'] .'</span>
				</p>
				<p class="itemtag">'.lang_tag.'：'. getTag($list['id'],$target) .'</p>				
				<p>'.lang_identifier.'：<span class="itemid">'.$id.'</span></p>
				<p class="itemstat">'.
					$task -> getFileTaskOngoing($list['id'])
				.'</p>
			</div>
		</td>'
		//.'<td align=center>'. date('Y-m-d',strtotime($list['time'])) .'</td>'
		.'<td align=center><span class="star">'.$starHtml.'</span></td>'
		//.'<td align=center>'. $list['hits'] .'</td>'
		//.'<td align=center>'. $list['downTimes'] .'</td>'
		//.'<td align=center>'. $list['comments'] .'</td>'
		.'<td>';
		
		$html .='<span class="action view"><a href="'.urlRewrite('option=media&id='.$id).'">'.lang_view.'</a></span>';
		
		if( $mediaFile -> isFileCanDel( $list['id']) )
			$html .='<span class="action del"><a href="'.WEB_ROOT_PATH.'?option=userDo&type=action&do=delFile&id='. $id.'">'.lang_del.'</a></span>';
		elseif( $user -> id() == $list['user_id'] || $user -> powder() >= 9 )
			$html .='<h4 class="disabled">'.lang_del.'</h4>';
		
		if( $mediaFile -> isFileCanEdit($list['id']) )
			$html .='<span class="action mod"><a href="'.urlRewrite('option=creatMedia&id='.$id).'">'.lang_edit.'</a></span>';
		elseif( $user -> id() == $list['user_id'] || $user -> powder() >= 9 )
			$html .='<h4 class="action disabled">'.lang_edit.'</h4>';
	 $html .='</td>'
	  .'</tr>'
	  .'<tr><td colspan="10" class="compart"><hr /></td></tr>';
	  
	  return $html ;

}


function checkBadWords( &$string ){
	$badWords = explode('|',BAD_WORDS) ;
	$html = str_replace( $badWords ,'***' , $string );
	return $html;
}

function loadEdit($obj,$editStle='task'){
	$html = '
<script type="text/javascript" src="'.JSLAB_PATH.'editor/wysiwyg.js"></script>
<script type="text/javascript" src="'.JSLAB_PATH.'editor/set.js"></script>
<script type="text/javascript"> $(function(){ creatWysiwyg("'.$obj.'","'. $editStle .'"); }); </script>
<link rel="stylesheet" href="'.JSLAB_PATH.'editor/wysiwyg.css" type="text/css" />
	';
	return $html;
}

function creatEdit($obj,$editStle='task'){
	$html = '
		<script type="text/javascript"> $(function(){ creatWysiwyg("'.$obj.'","'. $editStle .'"); }); </script>
	';
	return $html;
}





?>